﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Xml.Serialization;
using System.IO;
using KNXFramework.Logging;
using KNXFramework.KNXObjects;

namespace KNXFramework.Settings
{
    public static class KNXSettings
    {
        public static KNXObjects KNXObjects;
        static KNXSettings()
        {
            string filePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
            filePath += "\\Settings\\conf.xml";
            Uri fileUri = new Uri(filePath);
            
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(KNXObjects));
            CustomLogger.WriteInformationEntry("Load settings from file : " + fileUri.LocalPath);
            using (StreamReader sr = System.IO.File.OpenText(fileUri.LocalPath))
            {
                KNXObjects = xmlSerializer.Deserialize(sr) as KNXObjects;
                CustomLogger.WriteInformationEntry("Settings loaded. Number of objects found: " + KNXObjects.KNXObjectList.Count);
            }            
        }

        public static void LoadObjectsFromSettings(ObjectController controller)
        {
            foreach (KNXObject settingsObject in KNXObjects.KNXObjectList)
            {
                AddNewObject(settingsObject, controller);
            }
        }

        public static void AddNewObject(KNXObject settingsObject, ObjectController controller)
        {
            if (!controller.ContainsKey(settingsObject.Id))
            {
                KNXObjectBase obj = KNXObjectBase.GetConcreteObject(settingsObject, controller.KNXConnection);
                if (!controller.ContainsKey(settingsObject.Id))
                    controller.Add(obj.ID, obj);                
            }
            else
                throw new ApplicationException("An object with the same ID already exists");
        }
    }
}
